﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common.Model;
using Dapper.Contrib.Extensions;
using pinduoduo;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using Tk.Soc.Share.Common.Helpers;

namespace 拼多多小号检测
{
    public partial class Form1 : Form
    {
        private PddTokenService pddTokenService = new PddTokenService();
        private IList<PddToken> pddTokens = new List<PddToken>();

        public Form1()
        {
            InitializeComponent();
            this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);
            this.dataGridView1.AutoGenerateColumns = false;
            var tokens = pddTokenService.GetAllToken();
            pddTokens.Clear();
            pddTokens = pddTokens.Concat(tokens).ToList();

            this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());

        }


        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            ImportData(false);
        }

        private void ImportData(bool isEncodeAESToken)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }
                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var PddTokenList = pddTokenService.GetAllToken();
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);

                        if (sArray1.Length < 2)
                        {
                            continue;
                        }
                        string qqOrPhone = string.Empty;
                        string uid = string.Empty;
                        string token = string.Empty;
                        if (sArray1.Length == 2)
                        {
                            uid = sArray1[0];
                            token = sArray1[1];
                        }

                        if (sArray1.Length == 3)
                        {
                            qqOrPhone = sArray1[0];
                            uid = sArray1[1];
                            token = sArray1[2];
                        }
                        //string qqOrPhone = sArray1[0];
                        //string uid = sArray1[1];
                        //string token = sArray1[2];
                        PddToken pddToken = new PddToken();
                        pddToken.pdd_user_id = uid;
                        pddToken.PDDAccessToken = token;
                        var pddT = PddTokenList.Where(x =>
                        {
                            return x.pdd_user_id == uid;
                        }).FirstOrDefault();
                        if (pddT != null)
                        {
                            pddToken.id = pddT.id;
                            pddTokenService.UpdateToken(pddToken, isEncodeAESToken);
                            //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                        }
                        else
                        {
                            pddTokenService.InsertToken(pddToken, isEncodeAESToken);
                            //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入小号失败", ex);
                    }

                }

                var tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();

                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.AutoGenerateColumns = false;

            this.dataGridView1.AutoSize = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ImportData(true);
        }

        private async void button4_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetAllToken();
            foreach (var pddToken in tokens)
            {
                if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
                {
                    var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                    if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        pddToken.status = "正常";
                    }
                    else if (pddUserInfo.Content.Contains("error_code"))
                    {
                        pddToken.status = "过期";
                    }
                    else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        pddToken.status = "未知";
                    }
                }
                else
                {
                    pddToken.status = "未知";
                }

                pddTokenService.UpdateToken(pddToken, true);
                //if (string.IsNullOrWhiteSpace(pddUserInfo.Content))
                //{
                //    MessageBox.Show("获取用户信息异常，小号可能过期了");
                //    return;
                //}
            }

            tokens = pddTokenService.GetAllToken();
            pddTokens.Clear();
            pddTokens = pddTokens.Concat(tokens).ToList();
            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
        }

        private void button3_Click(object sender, EventArgs e)
        {

            int day = 13;
                int.TryParse(dayTextBox.Text,out day);
            var nowTime = DateTime.Now.AddDays(day);
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "小号 (*.txt)|*.txt";
            dialog.DefaultExt = ".txt";
            dialog.Title = "保存配置文件";

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filename = dialog.FileName;
                var tokens = pddTokenService.GetAllToken(false);
                StringBuilder str = new StringBuilder();
                foreach (var item in tokens)
                {
                    str.AppendLine("01----" + item.pdd_user_id + "----" + item.PDDAccessToken);
                }
                File.WriteAllText(filename, str.ToString());
            }


        }

        private void button7_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定删除吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                var tokens = pddTokenService.GetAllToken(false);
                foreach (var item in tokens)
                {
                    if (item.status == "过期")
                    {
                        pddTokenService.DelToken(item);
                    }
                }

                tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();
                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
            }

        }

        private void button6_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定删除吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                var tokens = pddTokenService.GetAllToken(false);
                foreach (var item in tokens)
                {
                    pddTokenService.DelToken(item);
                }

                tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();
                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());

            }
        }

        private async void button8_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定清空所有地址吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                var tokens = pddTokenService.GetAllToken(true);
                foreach (var item in tokens)
                {
                    if (item.status == "过期")
                    {
                        this.Msg.AppendText("小号过期了，跳过");
                    }
                    //this.Msg.AppendText("正在清除："+ item.pdd_user_id +"\r\n");
                    this.Msg.AppendText("正在获取所有地址："+ item.pdd_user_id + "\r\n");
                    var addresses = await PddApi.GetAllAddress(item);
                    if (addresses == null|| addresses.Count()==0) {
                        this.Msg.AppendText("获取到0个地址 \r\n");
                        continue;
                    }
                    this.Msg.AppendText("获取到"+ addresses.Count() + "个地址 \r\n");
                    foreach (var address in addresses)
                    {
                     
                        bool result = await PddApi.DelAddressById(item,address.address_id);
                        if (result) 
                        {
                            this.Msg.AppendText(address.name+ " " + address.mobile + " " + address.address+ "   删除成功\r\n");
                        }
                        else 
                        {
                            this.Msg.AppendText(address.address + "   删除失败\r\n");
                        }
                       
                    }
                }
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            var pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
            GetRegions(1, pddToken);
        }

        public async void GetRegions(int regionId, PddToken pddToken)
        {

            var res = await pinduoduo.PddApi.GetRegions(pddToken, regionId);
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var regions = JsonHelper.DeserializeObject<Regions>(res.Content);
                Console.WriteLine(res.Content);
                if (regions.regions == null) 
                {
                    return;
                }
               
                foreach (var regionItem in regions.regions)
                {
                    AreaModel areaModel = new AreaModel();
                    areaModel.parent_id = regionItem.parent_id;
                    areaModel.region_id = regionItem.region_id;
                    areaModel.region_name = regionItem.region_name;
                    areaModel.region_type = regionItem.region_type;
                    await DataBaseHelper.SqLiteDBCon.InsertAsync<AreaModel>(areaModel);

                    if (regionItem.region_type == 3)
                    {
                        continue;
                    }
                    GetRegions(regionItem.region_id, pddToken);
                }
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {

        }

        private void dayTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void button11_Click(object sender, EventArgs e)
        {
            int day = 13;
            int.TryParse(dayTextBox.Text, out day);
            var expire_date = DateTime.Now.AddDays(day);
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "小号 (*.sql)|*.sql";
            dialog.DefaultExt = ".txt";
            dialog.Title = "保存配置文件";

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filename = dialog.FileName;
                var tokens = pddTokenService.GetAllToken(false);
                StringBuilder str = new StringBuilder();
                foreach (var item in tokens)
                {
                    //string str = string.Format("{0}-{1}", 1, 2)
                    string sql = "INSERT INTO `pdd_token`(`pdd_user_id`, `pdd_access_token`, `status`, `create_time`, `expire_date`, `remark`) VALUES ('{0}', '{1}', {2}, '{3}', '{4}',  '{5}');";
                    string sqlStr = string.Format(sql, item.pdd_user_id, item.PDDAccessToken,0,DateTime.Now.ToString(), expire_date, BeiZhu.Text);
                    str.AppendLine(sqlStr);
                  // str.AppendLine("00----" + item.pdd_user_id + "----" + item.PDDAccessToken + "----" + AESHelper.EncodeAES(nowTime.ToString()));
                }
                File.WriteAllText(filename, str.ToString());
            }
        }
    }
}
